/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.YuYueEntity;
import io.renren.modules.app.service.YuYueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/")
@Api("获取oppid")
public class YuYueController {
    @Autowired
    YuYueService yuYueService;

    @PostMapping("/yuyue/unbind")
    @ResponseBody
    @ApiOperation("查询热门问题列表")
    public R unbind(@RequestBody PramsDtoB b) {
        QueryWrapper<YuYueEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("secret", b.getSecret());
        YuYueEntity one = yuYueService.getOne(queryWrapper);
        if (one == null) {
            return R.error();
        } else {
            if (!one.getOpenid().equals( b.getOpenid())) {
                return R.error();
            } else {
                one.setStatus(-1);
                one.setOpenid(null);
                yuYueService.updateById(one);
                return R.ok();
            }
        }
    }

    @PostMapping("/yuyue/bind")
    @ResponseBody
    @ApiOperation("绑定")
    public R bind(@RequestBody PramsDtoB b) {
        QueryWrapper<YuYueEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("secret", b.getSecret());
        YuYueEntity one = yuYueService.getOne(queryWrapper);
        if (one == null) {
            return R.error("邀请码不存在");
        } else {
            if (one.getOpenid() != null&&!one.getOpenid().equals("")) {
                return R.error("邀请码已失效");
            } else {
                one.setOpenid(b.getOpenid());
                one.setStatus(0);
                one.setCreateTime(new Date());
                yuYueService.updateById(one);
                return R.ok(one.getId());
            }
        }
    }

    private String get(String url, String param) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                //System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            //System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }

    @ApiOperation("获取openid")
    @PostMapping("/openid")
    @ResponseBody
    public R openid(@RequestBody PramsDtoA a) {
        String res = get(
                "https://api.weixin.qq.com/sns/jscode2session",
                "appid=" + a.getAppid() + "&secret=" + a.getSecret() + "&js_code=" + a.getJs_code() + "&grant_type=" + a.getGrant_type());
        JSONObject result = JSONObject.parseObject(res);
        String openid = result.getString("openid");
        if (openid == null) {
            return R.error();
        } else {
            return R.ok(openid);
        }
    }

    @ApiOperation("获取该用户已经申请的预约单")
    @PostMapping("/yuyue/get")
    @ResponseBody
    public R get(@RequestBody PramsDto pramsDto) {
        String openid = pramsDto.getOpenid();
        QueryWrapper<YuYueEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("status");
        queryWrapper.eq("openid", openid);

        return R.ok(yuYueService.list(queryWrapper));
    }

    @PostMapping("yuyue/{id}")
    @ApiOperation("根据id查询")
    public R getYuyue(@PathVariable String id) {
        YuYueEntity byId = yuYueService.getById(id);
        return R.ok(byId);
    }

    @ApiOperation("填写详细申请单")
    @PostMapping("/yuyue/save")
    @ResponseBody
    public R get(@RequestBody PramsDtoC pramsDto) {
        YuYueEntity byId = yuYueService.getById(pramsDto.getId());
        if (byId == null) {
            return R.error();
        }
        if (!byId.getOpenid().equals(pramsDto.getOpenid())) {
            return R.error();
        }
        byId.setStatus(1);

        byId.setName(pramsDto.getName());
        byId.setTelephone(pramsDto.getTelephone());
        //todo 其他信息
        yuYueService.updateById(byId);
        return R.ok();
    }

    @ApiOperation("查询热门问题列表")
    @PostMapping("/yuyue/appraise")
    @ResponseBody
    public R appraise(@RequestBody PramsDtoD pramsDto) {
        YuYueEntity byId = yuYueService.getById(pramsDto.getId());
        if (byId == null) {
            return R.error();
        }
        if (!byId.getOpenid().equals(pramsDto.getOpenid())) {
            return R.error();
        }
        byId.setStatus(3);
        byId.setStar(pramsDto.getStar());
        byId.setAppraise(pramsDto.getAppraise());
        yuYueService.updateById(byId);
        return R.ok();
    }

    @Data
    public static class PramsDto {
        private String openid;
    }

    @Data
    public static class PramsDtoC {
        private String name;
        private String telephone;
        private String openid;
        private String id;
    }

    @Data
    public static class PramsDtoA {
        String appid;
        String secret;
        String js_code;
        String grant_type;
    }


    @Data
    public static class PramsDtoB {
        String openid;
        String secret;
    }

    @Data
    public static class PramsDtoD {
        String id;
        String openid;
        int star;
        String appraise;
    }
}
